package suanfa;

public class Solution {
    int[] tmp;
    public int[] sortArray(int[] nums) {
        tmp=new int[nums.length];
        mergesort(nums,0,nums.length-1);
        return nums;
    }
    public void mergesort(int[] nums,int left,int right){
        if(left>=right) return;
        //1.根据中间点划分区域
        int mid=(left+right)/2;
        //2.先把左右区间排序
        mergesort(nums,left,mid);
        mergesort(nums,mid+1,right);
        //2.合并两个有序数组
        int cur1=left,cur2=mid+1,i=0;
        while(cur1<=mid && cur2<=right)
            tmp[i++]=nums[cur1] <=nums[cur2]? nums[cur1++]:nums[cur2++];
        //3.处理没有遍历完的数组
        while(cur1<=mid) tmp[i++]=nums[cur1++];
        while(cur2<=right) tmp[i++]=nums[cur2++];
        //4.还原
        for(int j=left;j<=right;j++){
            nums[j]=tmp[j-left];
        }
    }
}
